<!-- 修改个人信息页面 -->
<template>
  <view class="profile-edit">
    <!-- 头像 -->
    <view class="avatar-box" @click="chooseAvatar">
      <image :src="avatarPreview" class="avatar-img" mode="aspectFill" />
      <view class="avatar-overlay"><text class="icon">📷</text></view>
    </view>

    <!-- 表单区域 -->
    <view class="form-card">
      <view class="field">
        <text class="label">昵称</text>
        <input
          v-model.trim="nickname"
          placeholder="请输入昵称"
          maxlength="20"
          class="input"
        />
      </view>
      <view class="field multiline">
        <text class="label">个人简介</text>
        <textarea
          v-model.trim="bio"
          placeholder="填写一句话介绍"
          maxlength="100"
          auto-height
          class="textarea"
        />
      </view>
    </view>

    <button class="save-btn" @click="submit">保存</button>
  </view>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { http } from "@/pages/utils/Http";
import type { UserInfoResponse } from "@/pages/utils/request";

// 当前登录用户 ID
const userId: number = uni.getStorageSync("userId");

const avatarPreview = ref<string>("/static/images/logo.png");
const nickname = ref<string>("");
const bio = ref<string>("");

// 加载当前用户资料
const fetchProfile = async () => {
  if (!userId) {
    uni.showToast({ title: "用户未登录", icon: "none" });
    return;
  }
  try {
    const res = await http.get<UserInfoResponse>("/api/user/profile", {
      userId,
    });
    if (res.code === 200) {
      avatarPreview.value = res.data.avatar || "/static/images/logo.png";
      nickname.value = res.data.nickname || res.data.username;
      bio.value = res.data.bio || "";
    }
  } catch (e) {
    uni.showToast({ title: "加载用户信息失败", icon: "none" });
  }
};

onMounted(fetchProfile);

// 选择头像并转为 base64
const chooseAvatar = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ["original", "compressed"],
    sourceType: ["album", "camera"],
    success: (selRes) => {
      const filePath = selRes.tempFilePaths[0];

      // 非 H5，可使用 FileSystemManager 读取 base64
      // @ts-ignore
      if (typeof uni.getFileSystemManager === "function") {
        // #ifndef H5
        uni.getFileSystemManager().readFile({
          filePath,
          encoding: "base64",
          success: (readRes: any) => {
            avatarPreview.value = `data:image/png;base64,${readRes.data}`;
          },
          fail: () => {
            uni.showToast({ title: "读取图片失败", icon: "none" });
          },
        });
        // #endif
      } else {
        // H5 环境使用 FileReader 转 base64
        const file =
          (selRes as any).tempFiles?.[0]?.file ||
          (selRes as any).tempFiles?.[0];
        if (file) {
          const reader = new FileReader();
          reader.onload = (e: any) => {
            avatarPreview.value = e.target.result as string;
          };
          reader.onerror = () => {
            uni.showToast({ title: "读取图片失败", icon: "none" });
          };
          reader.readAsDataURL(file);
        } else {
          // fallback：直接使用本地路径作为预览，上传时再处理
          avatarPreview.value = filePath;
        }
      }
    },
  });
};

// 提交修改
const submit = async () => {
  if (!nickname.value) {
    uni.showToast({ title: "请输入昵称", icon: "none" });
    return;
  }
  try {
    const res = await http.post<any>("/api/user/update", {
      userId,
      nickname: nickname.value,
      avatar: avatarPreview.value,
      bio: bio.value,
    });
    if (res.code === 200) {
      uni.showToast({ title: "保存成功", icon: "success" });
      // 返回上一页并通知刷新
      uni.$emit("refreshMine");
      setTimeout(() => {
        uni.navigateBack();
      }, 500);
    }
  } catch (e) {
    uni.showToast({ title: "保存失败", icon: "none" });
  }
};
</script>

<style lang="scss" scoped>
.profile-edit {
  padding: 24px 30px 60px;
  font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-box {
  position: relative;
  margin-bottom: 28px;

  .avatar-img {
    width: 96px;
    height: 96px;
    border-radius: 50%;
    object-fit: cover;
    background: #f3f3f3;
    box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
  }

  .avatar-overlay {
    position: absolute;
    right: 0;
    bottom: 0;
    width: 28px;
    height: 28px;
    border-radius: 50%;
    background: #1976d2;
    display: flex;
    align-items: center;
    justify-content: center;
    .icon {
      color: #fff;
      font-size: 14px;
    }
  }
}

/* 卡片 */
.form-card {
  width: 100%;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  padding: 12px 16px;
  margin-bottom: 32px;
  box-sizing: border-box;
}

.field {
  display: flex;
  align-items: center;
  margin-bottom: 18px;

  &:last-child {
    margin-bottom: 0;
  }

  .label {
    width: 72px;
    font-size: 15px;
    color: #333;
  }

  .input {
    flex: 1;
    font-size: 15px;
    color: #333;
    padding: 10px 0;
    border: none;
    text-align: right;
  }

  &.multiline {
    align-items: flex-start;
    .textarea {
      flex: 1;
      font-size: 15px;
      color: #333;
      min-height: 80px;
      border: none;
      text-align: right;
    }
  }
}

.save-btn {
  width: 100%;
  height: 46px;
  line-height: 46px;
  background: linear-gradient(90deg, #6577ff, #6074ff);
  color: #fff;
  font-size: 16px;
  border-radius: 24px;
  text-align: center;
  box-shadow: 0 4px 12px rgba(96, 116, 255, 0.3);
}
</style>
